import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import { Execution, ExecuteScriptData } from '@/types/execution'
import * as executionAPI from '@/services/executionAPI'

interface ExecutionState {
  executions: Execution[]
  currentExecution: Execution | null
  loading: boolean
  error: string | null
  executing: boolean
  executionResult: {
    data: any[]
    columns: string[]
    rowCount: number
    executionTime: number
  } | null
}

const initialState: ExecutionState = {
  executions: [],
  currentExecution: null,
  loading: false,
  error: null,
  executing: false,
  executionResult: null,
}

// 异步thunks
export const executeScript = createAsyncThunk(
  'execution/executeScript',
  async (data: ExecuteScriptData) => {
    const response = await executionAPI.executeScript(data)
    return response.data
  }
)

export const fetchExecutions = createAsyncThunk(
  'execution/fetchExecutions',
  async (params?: {
    scriptId?: string
    connectionId?: string
    status?: string
    limit?: number
    offset?: number
  }) => {
    const response = await executionAPI.getExecutions(params)
    return response.data
  }
)

export const fetchExecutionById = createAsyncThunk(
  'execution/fetchExecutionById',
  async (id: string) => {
    const response = await executionAPI.getExecution(id)
    return response.data
  }
)

export const cancelExecution = createAsyncThunk(
  'execution/cancelExecution',
  async (id: string) => {
    const response = await executionAPI.cancelExecution(id)
    return response.data
  }
)

const executionSlice = createSlice({
  name: 'execution',
  initialState,
  reducers: {
    setCurrentExecution: (state, action: PayloadAction<Execution | null>) => {
      state.currentExecution = action.payload
    },
    clearExecutionResult: (state) => {
      state.executionResult = null
    },
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // executeScript
      .addCase(executeScript.pending, (state) => {
        state.executing = true
        state.error = null
        state.executionResult = null
      })
      .addCase(executeScript.fulfilled, (state, action) => {
        state.executing = false
        state.executionResult = action.payload.result
        state.currentExecution = action.payload.execution
      })
      .addCase(executeScript.rejected, (state, action) => {
        state.executing = false
        state.error = action.error.message || '脚本执行失败'
      })
      // fetchExecutions
      .addCase(fetchExecutions.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchExecutions.fulfilled, (state, action) => {
        state.loading = false
        state.executions = action.payload.executions || []
      })
      .addCase(fetchExecutions.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message || '获取执行历史失败'
      })
      // fetchExecutionById
      .addCase(fetchExecutionById.fulfilled, (state, action) => {
        state.currentExecution = action.payload
      })
      // cancelExecution
      .addCase(cancelExecution.fulfilled, (state, action) => {
        const index = state.executions.findIndex(e => e.id === action.payload.id)
        if (index !== -1) {
          state.executions[index] = action.payload
        }
        if (state.currentExecution?.id === action.payload.id) {
          state.currentExecution = action.payload
        }
      })
  },
})

export const {
  setCurrentExecution,
  clearExecutionResult,
  clearError,
} = executionSlice.actions

export default executionSlice.reducer